<template>
  <div class="account-list">
    <div class="account-list-header">
      <div class="header-left">
        <h3 class="header-title">我的账号</h3>
        <span class="account-count">共 {{ total }} 个账号</span>
      </div>
      <div class="header-actions">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索账号编号或描述"
          style="width: 200px; margin-right: 8px"
          @search="onSearch"
        />
        <a-select
          v-model:value="statusFilter"
          placeholder="状态筛选"
          style="width: 120px; margin-right: 8px"
          @change="onFilterChange"
          allowClear
        >
          <a-select-option value="">全部状态</a-select-option>
          <a-select-option value="待审核">待审核</a-select-option>
          <a-select-option value="已上架">已上架</a-select-option>
          <a-select-option value="已出租">已出租</a-select-option>
          <a-select-option value="审核失败">审核失败</a-select-option>
        </a-select>
        <a-button type="primary" @click="addAccount" style="margin-right: 8px">
          <template #icon><PlusOutlined /></template>
          添加账号
        </a-button>
        <a-button @click="refreshAccounts">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </div>
    </div>
    <a-spin :spinning="loading">
      <div class="accounts-grid">
        <div
          v-for="account in accounts"
          :key="account._id"
          class="account-card"
          @click="viewAccount(account)"
        >
          <!-- 卡片头部 -->
          <div class="card-header">
            <div class="account-basic-info">
              <div class="account-image-wrapper">
                <img :src="filterImage(account.image)" alt="账号图片" class="account-image" />
              </div>
              <div class="account-title-info">
                <div class="account-number">{{ account.number }}</div>
                <div class="account-tags">
                  <a-tag color="blue" size="small">{{ account.level }}级</a-tag>
                  <a-tag :color="account.server === 'QQ' ? 'blue' : 'green'" size="small">{{ account.server }}</a-tag>
                  <a-tag :color="account.loginMethod === '扫码登录' ? 'orange' : 'purple'" size="small">{{ account.loginMethod }}</a-tag>
                </div>
              </div>
            </div>
            <div class="status-price">
              <a-tag :color="getStatusColor(account.status)" class="status-tag">{{ account.status }}</a-tag>
              <div class="price-tag">
                <span class="price-value">¥{{ account.price }}</span>
              </div>
            </div>
          </div>
          
          <!-- 卡片内容 -->
          <div class="card-content">
            <div class="stats-grid">
              <!-- 纯币 -->
              <div class="stat-item">
                <span class="stat-label">纯币</span>
                <span class="stat-value">{{ account.coinAssets }}M</span>
              </div>
              <!-- 总资产 -->
              <div class="stat-item">
                <span class="stat-label">总资产</span>
                <span class="stat-value">{{ account.totalAssets }}M</span>
              </div>
              <!-- 保险箱 -->
              <div class="stat-item">
                <span class="stat-label">保险箱</span>
                <a-tag :color="getSafetyBoxColor(account.safetyBox)" size="small">{{ formatSafetyBox(account.safetyBox) }}</a-tag>
              </div>
              <!-- 体力 -->
              <div class="stat-item">
                <span class="stat-label">体力</span>
                <span class="stat-value">{{ account.energyLevel }}级</span>
              </div>
              <!-- 负重 -->
              <div class="stat-item">
                <span class="stat-label">负重</span>
                <span class="stat-value">{{ account.weightLevel }}级</span>
              </div>
              <!-- 段位 -->
              <div class="stat-item">
                <span class="stat-label">段位</span>
                <a-tag :color="getRankColor(account.rank)" size="small">{{ account.rank }}</a-tag>
              </div>
            </div>
            
            <!-- 刀皮信息 -->
            <div v-if="account.weaponSkins && account.weaponSkins.length > 0" class="weapon-skins-section">
              <span class="stat-label">刀皮:</span>
              <div class="weapon-skins">
                <a-tag v-for="skin in account.weaponSkins.slice(0, 2)" :key="skin" size="small" color="purple">{{ skin }}</a-tag>
                <span v-if="account.weaponSkins.length > 2" class="more-skins">+{{ account.weaponSkins.length - 2 }}</span>
              </div>
            </div>
            
            <!-- 时间信息 -->
            <div class="time-info">
              <div class="time-item">
                <span class="time-label">{{ account.updatedAt !== account.createdAt ? '更新时间:' : '创建时间:' }}</span>
                <span class="time-value">{{ formatTime(account.updatedAt !== account.createdAt ? account.updatedAt : account.createdAt) }}</span>
              </div>
            </div>
          </div>
          
          <!-- 卡片底部 -->
          <div class="card-footer">
            <a-space>
              <a-button 
                v-if="account.status === '已上架' || account.status === '已下架' || account.status === '已消耗'"
                type="primary" 
                size="small" 
                @click.stop="editAccount(account)"
              >
                <template #icon><EditOutlined /></template>
                编辑
              </a-button>
              
              <a-button 
                v-if="account.status === '已上架'"
                danger 
                size="small" 
                @click.stop="delistAccount(account)"
              >
                <template #icon><StopOutlined /></template>
                下架
              </a-button>
              
              <a-button size="small" @click.stop="viewAccount(account)">
                <template #icon><EyeOutlined /></template>
                查看
              </a-button>
              
              <a-popconfirm
                v-if="account.status !== '已出租'"
                title="确定要删除这个账号吗？"
                @confirm="deleteAccount(account)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button danger size="small" @click.stop>
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </div>
        </div>
      </div>
      <a-empty v-if="!loading && accounts.length === 0" description="暂无账号" />
      <div v-if="total > pageSize" class="pagination-wrapper">
        <a-pagination
          v-model:current="currentPage"
          v-model:pageSize="pageSize"
          :total="total"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :show-total="(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
          @change="onPageChange"
          @showSizeChange="onPageSizeChange"
        />
      </div>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import accountAPI from '~/api/account'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { PlusOutlined, ReloadOutlined, EditOutlined, EyeOutlined, DeleteOutlined, StopOutlined } from '@ant-design/icons-vue'

const router = useRouter()

const accounts = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(6)
const total = ref(0)
const searchKeyword = ref('')
const statusFilter = ref('')

const fetchAccounts = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value
    }
    
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    
    if (statusFilter.value) {
      params.status = statusFilter.value
    }
    
    const res = await accountAPI.getMyAccounts(params)
    if (res.code === 200 && res.data && res.data.list) {
      accounts.value = res.data.list
      total.value = res.data.total || 0
    } else {
      accounts.value = []
      total.value = 0
    }
  } catch (e) {
    message.error('获取账号失败')
    accounts.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const onPageChange = (page, size) => {
  currentPage.value = page
  pageSize.value = size
  fetchAccounts()
}

const onPageSizeChange = (_, size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchAccounts()
}

const onSearch = () => {
  currentPage.value = 1
  fetchAccounts()
}

const onFilterChange = () => {
  currentPage.value = 1
  fetchAccounts()
}

const viewAccount = (account) => {
  router.push(`/accounts/${account._id}`)
}


const addAccount = () => {
  router.push('/accounts/create')
}

const refreshAccounts = () => {
  fetchAccounts()
}

const editAccount = (account) => {
  router.push(`/accounts/create?id=${account._id}`)
}

const delistAccount = async (account) => {
  try {
    const res = await accountAPI.delistAccount(account._id, {
      reason: '用户主动下架'
    })
    if (res.code === 200 || res.status === 'success') {
      message.success('账号已下架')
      fetchAccounts()
    } else {
      message.error(res.message || '下架失败')
    }
  } catch (error) {
    console.error('下架失败:', error)
    message.error('下架失败')
  }
}

const deleteAccount = async (account) => {
  try {
    const res = await accountAPI.deleteAccount(account._id)
    if (res.code === 200) {
      message.success('账号已删除')
      fetchAccounts()
    } else {
      message.error(res.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
  }
}

const filterImage = (item) => {
  if (typeof item === 'string') {
    try {
      const arr = JSON.parse(item)
      return Array.isArray(arr) && arr.length > 0 ? arr[0] : ''
    } catch (e) {
      return ''
    }
  }
  return Array.isArray(item) && item.length > 0 ? item[0] : ''
}

const formatSafetyBox = (safetyBox) => {
  if (!safetyBox) return ''
  return safetyBox.replace('安全箱', '').trim()
}

const getStatusColor = (status) => {
  const colorMap = {
    '待审核': 'orange',
    '已上架': 'green',
    '已下架': 'red',
    '已出租': 'blue',
    '已售出': 'purple',
    '已消耗': 'gray'
  }
  return colorMap[status] || 'default'
}

const getRankColor = (rank) => {
  const colorMap = {
    '无段位': 'default',
    '青铜': 'brown',
    '白银': 'silver',
    '黄金': 'gold',
    '铂金': 'cyan',
    '钻石': 'blue',
    '黑鹰': 'purple',
    '三角洲巅峰': 'red'
  }
  return colorMap[rank] || 'default'
}

const getSafetyBoxColor = (safetyBox) => {
  const colorMap = {
    '顶级安全箱 (3x3)': 'red',
    '高级保险箱 (2x3)': 'orange',
    '进阶安全箱 (2x2)': 'blue',
    '基础安全箱 (1x2)': 'green'
  }
  return colorMap[safetyBox] || 'default'
}

import { formatDate } from '~/utils/dateUtils'

const formatTime = (time) => {
  if (!time) return ''
  return formatDate(time, 'YYYY-MM-DD HH:mm')
}

onMounted(() => {
  fetchAccounts()
})
</script>

<style scoped lang="scss">
.account-list {
  width: 100%;
  
  .account-list-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    padding: 16px 20px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .header-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }
      
      .account-count {
        font-size: 12px;
        color: #666;
        background: #f5f5f5;
        padding: 4px 12px;
        border-radius: 16px;
        margin-right: 16px;
      }
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
  
  .accounts-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 12px;
    margin-bottom: 24px;
    
    .account-card {
      border: 1px solid #e8e8e8;
      border-radius: 12px;
      background: #fff;
      transition: all 0.3s ease;
      cursor: pointer;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      
      &:hover {
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
        border-color: #165dff;
      }
      
      .card-header {
        padding: 12px;
        border-bottom: 1px solid #f5f5f5;
        
        .account-basic-info {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 8px;
          
          .account-image-wrapper {
            .account-image {
              width: 40px;
              height: 40px;
              object-fit: cover;
              border-radius: 6px;
              border: 1px solid #e8e8e8;
            }
          }
          
          .account-title-info {
            flex: 1;
            
            .account-number {
              font-size: 14px;
              font-weight: 600;
              color: #333;
              margin-bottom: 4px;
              line-height: 1.2;
            }
            
            .account-tags {
              display: flex;
              gap: 4px;
              flex-wrap: wrap;
            }
          }
        }
        
        .status-price {
          display: flex;
          align-items: center;
          justify-content: space-between;
          
          .status-tag {
            font-weight: 500;
          }
          
          .price-tag {
            .price-value {
              background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
              color: white;
              font-size: 13px;
              font-weight: 700;
              padding: 4px 10px;
              border-radius: 12px;
              box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
            }
          }
        }
      }
      
      .card-content {
        padding: 12px;
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8px;
        
        .stats-grid {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 6px 8px;
          
          .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            min-height: 36px;
            padding: 4px;
            
            .stat-label {
              font-size: 10px;
              color: #999;
              font-weight: 500;
              margin-bottom: 2px;
            }
            
            .stat-value {
              font-size: 12px;
              color: #333;
              font-weight: 600;
            }
          }
        }
        
        .appearance-section,
        .weapon-skins-section {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 6px 0;
          border-top: 1px solid #f5f5f5;
          
          .stat-label {
            font-size: 10px;
            color: #888;
            font-weight: 500;
            white-space: nowrap;
          }
          
          .appearance-text {
            font-size: 11px;
            color: #333;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .weapon-skins {
            display: flex;
            gap: 4px;
            align-items: center;
            flex-wrap: wrap;
            flex: 1;
            
            .more-skins {
              font-size: 11px;
              color: #666;
              background: #f5f5f5;
              padding: 2px 6px;
              border-radius: 8px;
            }
          }
        }
        
        .time-info {
          margin-top: auto;
          padding-top: 6px;
          border-top: 1px solid #f5f5f5;
          
          .time-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .time-label {
              font-size: 10px;
              color: #999;
            }
            
            .time-value {
              font-size: 10px;
              color: #666;
            }
          }
        }
      }
      
      .card-footer {
        padding: 8px 12px;
        border-top: 1px solid #f5f5f5;
        
        .ant-btn {
          height: 24px;
          border-radius: 4px;
          font-weight: 500;
          font-size: 11px;
          padding: 0 8px;
        }
      }
    }
  }
  
  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 24px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
  }
}

// 移动端适配
@media (max-width: 768px) {
  .account-list {
    * {
      box-sizing: border-box;
    }
    .account-list-header {
      flex-direction: column;
      gap: 16px;
      padding: 12px 16px;
      margin-bottom: 16px;
      
      .header-left {
        width: 100%;
        justify-content: space-between;
        
        .header-title {
          font-size: 16px;
        }
        
        .account-count {
          font-size: 11px;
          margin-right: 0;
        }
      }
      
      .header-actions {
        width: 100%;
        flex-direction: column;
        gap: 8px;
        
        .ant-input-search,
        .ant-select {
          width: 100% !important;
          margin: 0 !important;
        }
        
        .ant-btn {
          width: 100%;
          height: 44px;
          font-size: 14px;
          margin: 0 !important;
        }
      }
    }
    
    .accounts-grid {
      grid-template-columns: 1fr;
      gap: 12px;
      
      .account-card {
        .card-header {
          padding: 12px 16px;
          
          .account-basic-info {
            .account-image-wrapper .account-image {
              width: 50px;
              height: 50px;
            }
            
            .account-title-info {
              .account-number {
                font-size: 15px;
              }
              
              .account-tags {
                gap: 6px;
                
                .ant-tag {
                  font-size: 11px;
                  padding: 2px 6px;
                }
              }
            }
          }
          
          .status-price {
            margin-top: 8px;
            
            .status-tag {
              font-size: 12px;
            }
            
            .price-tag .price-value {
              font-size: 14px;
              padding: 6px 12px;
            }
          }
        }
        
        .card-content {
          padding: 12px 16px;
          
          .stats-grid {
            grid-template-columns: repeat(2, 1fr);
            gap: 12px 16px;
            
            .stat-item {
              min-height: 40px;
              padding: 8px;
              background: #f8f9fa;
              border-radius: 6px;
              
              .stat-label {
                font-size: 11px;
                margin-bottom: 4px;
              }
              
              .stat-value {
                font-size: 13px;
              }
            }
          }
          
          .weapon-skins-section {
            padding: 8px 0;
            flex-wrap: wrap;
            
            .stat-label {
              font-size: 11px;
              width: 100%;
              margin-bottom: 4px;
            }
            
            .weapon-skins {
              width: 100%;
              
              .ant-tag {
                font-size: 10px;
                margin: 2px;
              }
              
              .more-skins {
                font-size: 10px;
              }
            }
          }
          
          .time-info {
            padding-top: 8px;
            
            .time-item {
              .time-label,
              .time-value {
                font-size: 11px;
              }
            }
          }
        }
        
        .card-footer {
          padding: 12px 16px;
          
          .ant-space {
            width: 100%;
            justify-content: space-between;
            
            .ant-btn {
              height: 32px;
              font-size: 12px;
              padding: 0 12px;
              flex: 1;
              min-width: 60px;
            }
          }
        }
      }
    }
    
    .pagination-wrapper {
      margin-top: 16px;
      padding-top: 16px;
      
      :deep(.ant-pagination) {
        .ant-pagination-item,
        .ant-pagination-prev,
        .ant-pagination-next {
          min-width: 36px;
          height: 36px;
          line-height: 36px;
        }
        
        .ant-pagination-options {
          .ant-select {
            min-width: 80px;
          }
        }
      }
    }
  }
}

// 超小屏幕适配
@media (max-width: 480px) {
  .account-list {
    * {
      box-sizing: border-box;
    }
    .account-list-header {
      padding: 8px 12px;
      
      .header-left .header-title {
        font-size: 15px;
      }
      
      .header-actions .ant-btn {
        height: 42px;
        font-size: 13px;
      }
    }
    
    .accounts-grid {
      gap: 8px;
      
      .account-card {
        .card-header {
          padding: 10px 12px;
          
          .account-basic-info {
            .account-image-wrapper .account-image {
              width: 45px;
              height: 45px;
            }
            
            .account-title-info {
              .account-number {
                font-size: 14px;
              }
            }
          }
          
          .status-price .price-tag .price-value {
            font-size: 13px;
            padding: 4px 10px;
          }
        }
        
        .card-content {
          padding: 10px 12px;
          
          .stats-grid {
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            
            .stat-item {
              min-height: 36px;
              padding: 6px;
              
              .stat-label {
                font-size: 10px;
              }
              
              .stat-value {
                font-size: 12px;
              }
            }
          }
        }
        
        .card-footer {
          padding: 8px 12px;
          
          .ant-space .ant-btn {
            height: 28px;
            font-size: 11px;
            padding: 0 8px;
            min-width: 50px;
          }
        }
      }
    }
  }
}
</style>